<template>
   <!-- 页头 -->
   <el-page-header :icon="ArrowLeft" title="返回" @back="$router.go(-1)">
          <template #content>
            <span class="text-large font-600 mr-3"> {{$route.meta.title}} </span>
          </template>
        </el-page-header>
        
  <div class="message-container">
    <!-- 搜索条件区域 -->
    <el-card class="search-area">
      <el-form :model="searchForm" ref="searchFormRef" :inline="false" class="search-form">
        <el-form-item label="发件人" prop="appointorName">
          <el-input 
            v-model="searchForm.appointorName" 
            placeholder="请输入发件人" 
            clearable 
          />
        </el-form-item>
        <el-form-item label="主题" prop="title">
          <el-input 
            v-model="searchForm.title" 
            placeholder="请输入主题" 
            clearable 
          />
        </el-form-item>
        <el-form-item label="时间" prop="timeRange">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="x"
            class="date-picker"
          />
        </el-form-item>
        <el-form-item class="button-group">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="default" @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表操作区域 -->
    <el-card class="table-area">
      <div class="table-operations">
        <div class="operation-group">
          <el-button type="primary" @click="markAsRead">标记已读</el-button>
          <el-button type="success" @click="markAllAsRead">全部已读</el-button>
        </div>
        <div class="operation-group">
          <el-button type="danger" @click="batchDelete">批量删除</el-button>
          <el-button @click="refreshList">刷新</el-button>
        </div>
      </div>

      <!-- 消息列表 -->
      <el-table
        :data="messageList"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        class="message-table"
      >
        <el-table-column type="selection" width="55" />  
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag
              :type="scope.row.statusId === '0' ? 'danger' : 'info'"
              size="small"
              effect="plain"
            >
              {{ scope.row.statusId === '0' ? '未读' : '已读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="appointorName" label="发件人" min-width="100" />
        <el-table-column 
          prop="title" 
          label="主题" 
          min-width="120"
        >
          <template #default="scope">
            <span :class="{ 'unread-message': scope.row.statusId === '0' }">
              {{ addSuffix(scope.row, null, scope.row.title) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column 
          prop="content" 
          label="内容" 
          show-overflow-tooltip 
          min-width="150"
        >
          <template #default="scope">
            <span :class="{ 'unread-message': scope.row.statusId === '0' }">
              {{ scope.row.content }}
            </span>
          </template>
        </el-table-column>
        <el-table-column 
          prop="createTime" 
          label="通知时间" 
          min-width="120"
          :class-name="'time-column'"
        >
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination-component"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { api } from '@/api/api.config'
import { deleteMessage, readMessage } from '@/api'
import { useLoginStore } from '@/store/login'
import { useRouter } from 'vue-router'

const loginStore = useLoginStore()
const router = useRouter()

// 主题后缀
const addSuffix = (row, column, cellValue, index) => {
    return cellValue ? `${cellValue} 任务提醒` : '';
  }

// 搜索表单数据
const searchForm = reactive({
  appointorName: '',  // 改为发件人姓名
  title: '',        // 标题
  timeRange: []     // 时间范围
})

// 表格数据
const messageList = ref([])
const loading = ref(false)
const selectedMessages = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单引用
const searchFormRef = ref()

// 重置表单
const resetForm = () => {
  // 重置表单字段
  searchFormRef.value?.resetFields()
  // 重置分页
  currentPage.value = 1
  pageSize.value = 10
  // 重新获取数据
  fetchMessageList()
  // 清空选中
  selectedMessages.value = []
}

// 查询
const handleSearch = () => {
  currentPage.value = 1 // 重置页码
  fetchMessageList()
}

// 修改标记已读方法
const markAsRead = async () => {
  if (selectedMessages.value.length === 0) {
    ElMessage.warning('请选择要标记的消息')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要标记选中的 ${selectedMessages.value.length} 条消息为已读吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      }
    )

    // 获取选中消息的ID数组
    const messageIds = selectedMessages.value.map(message => message.messageId)
    console.log('标记已读的消息IDs:', messageIds)
    
    const response = await readMessage(messageIds)  // 直接传递ID数组
    console.log('标记已读响应:', response.data)

    if (response.data.code === 200) {
      ElMessage.success('标记已读成功')
      fetchMessageList()
      selectedMessages.value = []
    } else {
      ElMessage.error(response.data.message || '标记已读失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('标记已读出错：', error)
      ElMessage.error('标记已读失败，请稍后重试')
    }
  }
}

// 修改全部标记已读方法
const markAllAsRead = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要将所有消息标记为已读吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      }
    )

    // 获取所有未读消息的ID
    const unreadMessageIds = messageList.value
      .filter(message => message.statusId === '0')
      .map(message => message.messageId)

    if (unreadMessageIds.length === 0) {
      ElMessage.info('没有未读消息')
      return
    }

    console.log('全部标记已读的消息IDs:', unreadMessageIds)
    
    const response = await readMessage(unreadMessageIds)  // 直接传递ID数组
    console.log('全部标记已读响应:', response.data)

    if (response.data.code === 200) {
      ElMessage.success('全部标记已读成功')
      fetchMessageList()
      selectedMessages.value = []
    } else {
      ElMessage.error(response.data.message || '标记已读失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('标记全部已读出错：', error)
      ElMessage.error('标记已读失败，请稍后重试')
    }
  }
}

// 修改批量删除方法
const batchDelete = async () => {
  if (selectedMessages.value.length === 0) {
    ElMessage.warning('请选择要删除的消息')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedMessages.value.length} 条消息吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 获取消息ID数组
    const messageIds = selectedMessages.value.map(message => message.messageId)
    console.log('批量删除的消息IDs:', messageIds)
    
    const response = await deleteMessage(messageIds)  // 直接传递ID数组
    console.log('批量删除响应:', response.data)

    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      fetchMessageList()
      selectedMessages.value = []
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除消息出错：', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 修改单个删除方法
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条消息吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    console.log('单个删除的消息:', row)
    console.log('单个删除的消息ID:', row.messageId)
    
    const response = await deleteMessage([row.messageId])  // 传入单个ID的数组
    console.log('单个删除响应:', response.data)

    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      fetchMessageList()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除消息出错：', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 刷新列表
const refreshList = () => {
  fetchMessageList()
}

// 表格选择改变
const handleSelectionChange = (selection) => {
  selectedMessages.value = selection
}

// 获取消息列表
const fetchMessageList = async () => {
  loading.value = true
  try {
    const userId = loginStore.userInfo?.data?.userId
    
    if (!userId) {
      ElMessage.warning('未获取到用户ID')
      return
    }

    // 构造基础参数
    let params = {
      userId,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }

    // 处理搜索条件
    if (searchForm.appointorName) {
      params.appointorName = searchForm.appointorName
    }
    if (searchForm.title) {
      params.title = searchForm.title
    }

    // 修改时间处理逻辑
    if (searchForm.timeRange?.length === 2) {
      // 直接使用时间戳
      params.startTime = Number(searchForm.timeRange[0])
      params.endTime = Number(searchForm.timeRange[1])

      console.log('时间戳:', {
        startTime: params.startTime,
        endTime: params.endTime
      })
    }

    console.log('请求参数:', params)

    const response = await api({
      url: '/api/getMyMessage',
      method: 'get',
      params
    })

    console.log('获取到的消息列表数据：', response.data)

    if (response.data.code === 200) {
      messageList.value = response.data.data.list || []
      total.value = response.data.data.total || 0
    } else {
      ElMessage.error(response.data.message || '获取消息列表失败')
    }
  } catch (error) {
    console.error('获取消息列表出错：', error)
    ElMessage.error('获取消息列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchMessageList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchMessageList()
}

// 初始化时获取消息列表
onMounted(() => {
  fetchMessageList()
})

// 添加日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '-'
  
  try {
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    
    return `${year}-${month}-${day}`
  } catch (error) {
    console.error('日期格式化错误:', error)
    return dateString
  }
}

// 添加返回方法
const goBack = () => {
  router.back()
}
</script>

<style scoped>
.message-container {
  padding: 10px;
  width: 100%;
  box-sizing: border-box;
}

.search-area {
  margin-bottom: 15px;
}

.search-form {
  display: flex;
  flex-direction: column;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 15px;
  width: 100%;
}

.search-form :deep(.el-input) {
  width: 100%;
}

.date-picker {
  width: 100%;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.table-area {
  .table-operations {
    margin-bottom: 15px;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .operation-group {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }
}

.message-table {
  width: 100%;
  overflow-x: auto;
}

/* 移动端优化表格显示 */
@media screen and (max-width: 768px) {
  .message-container {
    padding: 5px;
  }

  .table-operations {
    flex-direction: column;
  }

  /* 调整按钮大小 */
  :deep(.el-button) {
    padding: 8px 15px;
    font-size: 14px;
  }

  /* 隐藏部分列 */
  :deep(.content-column) {
    display: none;
  }

  :deep(.time-column) {
    max-width: 100px;
  }

  /* 调整分页组件 */
  .pagination-component {
    :deep(.el-pagination__sizes) {
      display: none;
    }
    :deep(.el-pagination__jump) {
      display: none;
    }
  }
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

/* 表格内容溢出处理 */
:deep(.el-table) {
  .cell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

/* 响应式布局调整 */
@media screen and (min-width: 769px) {
  .search-form {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
  }

  .button-group {
    justify-content: flex-start;
  }

  .pagination {
    justify-content: flex-end;
  }
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 10px;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .button-group {
    flex-wrap: wrap;
  }
  
  .button-group .el-button {
    flex: 1;
    min-width: 80px;
  }
}

/* 加未读消息的样式 */
.unread-message {
  font-weight: bold;
  color: #303133;
}

/* 添加已读消息的样式 */
:deep(.el-table .read-message) {
  color: #909399;
}

/* 状态标签的样式调整 */
:deep(.el-tag) {
  margin: 0 2px;
}

/* 确保表格内容垂直居中 */
:deep(.el-table td) {
  vertical-align: middle;
}
</style>
